var last_alive_time = 0;
var alive_interval = null;

/**
 * websocket通用js
 * @param options
 * @constructor
 */
function WSConnect(options) {
    var defaults = {
        socket_ip: '0.0.0.0',//socket地址
        socket_port: '8080',//socket端口
        heartbeat: 60,//心跳时间
        debug: false//是否开启调试模式
    };
    this.opts = $.extend({}, defaults, options);
}

WSConnect.prototype.reconnect_times = 1;
WSConnect.prototype.socket = null;
WSConnect.prototype.socket_addr = "";
WSConnect.prototype.origin_val = "";
WSConnect.prototype.send_message = "";
WSConnect.prototype.heart_message = {"action":"heartbeat", "data":"heartpacket"};

//初始化
WSConnect.prototype.init = function (message) {
    var self = this;
    this.origin_val = message;
    this.send_message = JSON.stringify(message);
    this.socket_addr = "ws://" + this.opts.socket_ip + ":" + this.opts.socket_port;
    try {
        this.socket = new WebSocket(self.socket_addr);
        this.log(this.socket_addr + " trying connect.");
        //打开websocket连接
        this.socket.onopen = function () {
            if (self.send_message != "") {
                //发送普通消息
                self.log("initData:" + self.send_message);
                self.socket.send(self.send_message);
            }
            //发送心跳数据
            start_slive_monitor(self);
        };
    } catch (exception) {
        if (typeof exception == "object") {
            exception = exception.toString();
        }
        self.log("connecting exception, exception is " + exception);
    }

    return this.socket;
};

//socket发送数据
WSConnect.prototype.sendMessage = function (message) {
    this.log(message);
    if (this.socket != null) {
        message = JSON.stringify(message);
        this.log("send socket message info is " + message);
        this.socket.send(message);
    }
};

//重连websocket
WSConnect.prototype.reconnect = function () {
    if (this.reconnect_times <= 5) {
        this.socket_addr = "ws://" + this.opts.socket_ip + ":" + this.opts.socket_port;
        try {
            this.socket = new WebSocket(this.socket_addr);
            this.log(this.socket_addr + " trying reconnect, reconnect times is " + this.reconnect_times + " times.");
        } catch (exception) {
            if (typeof exception == "object") {
                exception = exception.toString();
            }
            this.log("connecting exception, exception is " + exception);
        }
        this.reconnect_times ++;
    }

    return this.socket;
};

//关闭socket
WSConnect.prototype.close = function () {
    if (this.socket != null) {
        this.log("websocket disconnect.");
        this.socket.close();
    }
};

//打印调试信息
WSConnect.prototype.log = function (logmessage) {
    if (this.opts.debug) {
        console.log(logmessage);
    }
};

WSConnect.prototype.setHeartTime = function () {
    last_alive_time = get_now_time();
    this.log("receive heart message time is " + last_alive_time);
};

//开始心跳
function start_slive_monitor(websocket) {
    if (alive_interval != null) {
        clearInterval(alive_interval);
    }
    //首先发送一次心跳包，获得第一次心跳包接收时间
    websocket.sendMessage(websocket.heart_message);
    alive_interval = setInterval(function () {
        websocket.log("send heartbeat message is " + websocket.heart_message);
        websocket.sendMessage(websocket.heart_message);
        console.info(last_alive_time);
        if (last_alive_time != 0 && (get_now_time() - last_alive_time >= parseInt(websocket.opts.heartbeat))) {
            //已断开，重新连接，已失去响应或连接
            websocket.reconnect();//连接上就发送心跳包
            websocket.sendMessage(websocket.heart_message);
        }
    }, 20000);//超过一分钟重连
}

//获取当前时间
function get_now_time()
{
    var date = new Date();
    var time = Date.parse(date.toString());
    return time/1000;
}